package com.ifacebox.face.track.sevice;

import com.google.common.io.Files;
import com.ifacebox.face.track.cache.FaceUserCache;
import com.ifacebox.face.track.model.FaceConfig;
import com.ifacebox.face.track.utils.JsonUtils;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

/**
 * @author znn
 */
public class FaceConfigService {
    private static final String CONFIG_NAME = "face_track_config.dat";
    private static final String UTF_8 = "UTF-8";
    private static final String URL_JAR = ".jar";

    public FaceConfigService() {
        try {
            if (!new File(this.getConfig(), CONFIG_NAME).exists()) {
                FaceConfig faceConfig = new FaceConfig();
                faceConfig.setCacheDir(new File(this.getConfig(), FaceUserCache.CACHE_DIR));
                faceConfig.setFaceScore(FaceEngineService.FACE_THRESHOLD);
                faceConfig.setAppId(FaceEngineService.APP_ID);
                faceConfig.setSdkKey(FaceEngineService.SDK_KEY);
                this.writeConfig(faceConfig);
            }
        } catch (IOException e) {
            throw new RuntimeException(String.format("初始化配置异常！(%s)", e.getMessage()));
        }
    }

    public FaceConfig readConfig() throws IOException {
        return this.readConfig(new File(this.getConfig(), CONFIG_NAME));
    }

    public FaceConfig readConfig(File fileConfig) throws IOException {
        return JsonUtils.fromJson(Files.toByteArray(fileConfig), FaceConfig.class);
    }

    public void writeConfig(FaceConfig faceConfig) throws IOException {
        this.writeConfig(faceConfig, new File(this.getConfig(), CONFIG_NAME));
    }

    public void writeConfig(FaceConfig faceConfig, File fileConfig) throws IOException {
        Files.write(JsonUtils.toJson(faceConfig).getBytes(StandardCharsets.UTF_8), fileConfig);
    }

    public File getConfig() throws IOException {
        String config = URLDecoder.decode(getClass().getProtectionDomain().getCodeSource().getLocation().getPath(), UTF_8);
        if (config.endsWith(URL_JAR)) {
            config = config.substring(0, config.lastIndexOf("/") + 1);
        }
        return new File(config);
    }
}
